const [request, crypto, fs] = [
  require('request-promise-native'),
  require('crypto'),
  require('fs')
]
const htmlOutModel = require('../template/genHtml.js')

let workspaceMap = {
  '44560965': '企业版',
  '50263871': '豪华商城',
  '45830188': '分销',
  '58998923': '福田政府项目'
}
const dateGap = 1000 * 3600 * 24

async function req (
  url = url,
  data,
  method = 'POST',
  headers = {
    'Content-Type': 'application/json'
  },
  proxy
) {
  let body = await request({
    method: method,
    url: url,
    responseType: 'json',
    timeout: 5000,
    proxy: proxy,
    headers: headers,
    data: data
  })
  return body
}
// tapd 签名+api调用
async function getTapd (projectId) {
  const account = 'kuN6fn5t'
  const pwd = '777A80F3-9AA6-DF49-90FB-F790060BB38D'

  const url = `https://api.tapd.cn/tasks?workspace_id=${projectId}&status=progressing|open&limit=200`
  const r = await req(url, {}, 'GET', {
    'Content-Type': 'application/json',
    Authorization:
      'Basic ' + Buffer.from(account + ':' + pwd).toString('base64')
  })
  return r
}
function task2Obj (taskArr) {
  const arr = []
  for (let i = 0; i < taskArr.length; i++) {
    let ownerArr = (taskArr[i].Task.owner || '').split(';')
    ownerArr.pop()

    let taskObj = {
      id: taskArr[i].Task.id,
      name: taskArr[i].Task.name,
      owner: taskArr[i].Task.owner || '<font color ="red">无</font>',
      creator: taskArr[i].Task.creator,
      begin: taskArr[i].Task.begin,
      due: taskArr[i].Task.due,
      description: taskArr[i].Task.description,
      workspace_id: taskArr[i].Task.workspace_id
    }
    // 将项目多个人的情况展开
    if (ownerArr.length > 1) {
      for (let d = 0; d < ownerArr.length; d++) {
        taskObj.owner = ownerArr[d] || '<font color ="red">无</font>'
        arr.push(JSON.parse(JSON.stringify(taskObj))) //copy一个对象
      }
    } else {
      taskObj.owner = taskObj.owner.replaceAll(';', '') //一个用户的时候把;过滤掉
      arr.push(taskObj)
    }
  }

  return arr
}
//生成htmlgrid
function genHtmlGrid (gridObj, titleArr, title, processFunc) {
  let obj = gridObj
  return htmlOutModel.gridTable(title, [
    {
      title: title,
      dataTitleArr: titleArr,
      dataArr: processFunc(obj)
    }
  ])
}
//时间数组生成
function taskItemAddDate (taskArr, startDate, endDate) {
  let sDate = new Date(startDate.date2Str().split(' ')[0])
  let eDate = new Date(endDate.date2Str().split(' ')[0])
  //console.log(sDate, eDate)
  //dateFlag -3 日期全无 -1 只有开始  -2 只有结束  1正常
  let dateStr = ''
  for (let i = 0; i < taskArr.length; i++) {
    const obj = {}
    let item = taskArr[i]
    item.dateFlag = 0
    if (item.begin === null && item.due === null) {
      item.dateFlag = -3
      let o = Array(30).fill(0)
      o.map((x, idx) => {
        obj['date' + idx] = x
      })
      Object.assign(item, obj)
    }
    if (item.begin && item.due === null) {
      item.dateFlag = -1

      if (new Date(item.begin) < sDate || new Date(item.begin) >= eDate) {
        let o = Array(30).fill(0)
        o.map((x, idx) => {
          obj['date' + idx] = x
        })
        Object.assign(item, obj)
      } else {
        const diffDate = ((new Date(item.begin) - sDate) / dateGap) | 0
        //console.log(diffDate)
        let o
        o = [
          ...Array(diffDate).fill(0),
          ...Array(1).fill(-1),
          ...Array(29 - diffDate).fill(0)
        ]
        o.map((x, idx) => {
          obj['date' + idx] = x
        })
        Object.assign(item, obj)
      }
      //console.log('begin', item)
    }
    if (item.begin === null && item.due) {
      item.dateFlag = -2
      if (new Date(item.due) < sDate || new Date(item.due) >= eDate) {
        let o = Array(30).fill(0)
        o.map((x, idx) => {
          obj['date' + idx] = x
        })
        Object.assign(item, obj)
      } else {
        const diffDate = ((new Date(item.due) - sDate) / dateGap) | 0
        //console.log(diffDate)
        let o
        o = [
          ...Array(diffDate).fill(0),
          ...Array(1).fill(-2),
          ...Array(29 - diffDate).fill(0)
        ]
        o.map((x, idx) => {
          obj['date' + idx] = x
        })
        Object.assign(item, obj)
      }
      //console.log('due', item)
    }
    if (item.begin && item.due) {
      item.dateFlag = 1
      const diffStartDate = ((new Date(item.begin) - sDate) / dateGap) | 0
      const diffEndDate = ((new Date(item.due) - eDate) / dateGap) | 0
      const diffSE = ((new Date(item.due) - new Date(item.begin)) / dateGap) | 0
      //console.log(new Date(item.begin), eDate)
      if (new Date(item.begin) >= eDate) {
        //开始日期大于时间轴结束日期
        let o = Array(30).fill(0)
        o.map((x, idx) => {
          obj['date' + idx] = x
        })
        Object.assign(item, obj)
      }
      if (new Date(item.begin) < sDate) {
        //开始日期小于时间轴开始日期
        if (new Date(item.due) < sDate) {
          let o = Array(30).fill(0)
          o.map((x, idx) => {
            obj['date' + idx] = x
          })
          Object.assign(item, obj)
        }
        if (new Date(item.due) >= eDate) {
          let o = Array(30).fill(1)
          o.map((x, idx) => {
            obj['date' + idx] = x
          })
          Object.assign(item, obj)
        }
        if (new Date(item.due) >= sDate && new Date(item.due) < eDate) {
          let o = [
            ...Array(31 + diffEndDate).fill(1),
            ...Array(-diffEndDate - 1).fill(0)
          ]
          o.map((x, idx) => {
            obj['date' + idx] = x
          })
          Object.assign(item, obj)
        }
      }
      if (new Date(item.begin) >= sDate && new Date(item.begin) < eDate) {
        if (new Date(item.due) < eDate) {
          let o = [
            ...Array(diffStartDate + 1).fill(0),
            ...Array(diffSE + 1).fill(1),
            ...Array(28 - diffSE - diffStartDate).fill(0)
          ]
          o.map((x, idx) => {
            obj['date' + idx] = x
          })
          Object.assign(item, obj)
        }
        if (new Date(item.due) >= eDate) {
          let o = [
            ...Array(diffStartDate).fill(0),
            ...Array(30 - diffStartDate).fill(1)
          ]
          o.map((x, idx) => {
            obj['date' + idx] = x
          })
          Object.assign(item, obj)
        }
      }
    }
  }
  // console.log(taskTotalArr.orderBy(['owner'], ['desc']))
  //console.log(startDate, endDate)
  return taskArr
}
//处理人到项目合并
function processPersonProjectCount (o) {
  let n = 1
  let owner = ''
  let data = o.map(item => {
    item.owner = (item.owner || '无').replaceAll(';', '')
    let obj = [
      n++,
      owner !== item.owner ? item.owner : '&nbsp;',
      workspaceMap[item.workspace_id],
      item.taskCount
    ]
    owner = item.owner
    for (let i = 0; i < 30; i++) {
      let val //=item['date' + i]
      switch (item['date' + i]) {
        case 0:
          val = '&nbsp;'
          break
        case -1:
          val =
            '<div style="height:100%;margin:-8px;color:#CD2626;background:#CD2626">&nbsp;</div>'
          break
        case -2:
          val =
            '<div style="height:100%;margin:-8px;color:#CD2626;background:#CD2626">&nbsp;</div>'
          break
        case 1:
          val =
            '<div style="height:100%;margin:-8px;color:#B3EE3A;background:#B3EE3A">&nbsp;</div>'
          break
        default:
          val = `<div style="text-align:center;height:100%;margin:-8px;color:#666666;background:#B3EE3A;">${
            item['date' + i]
          }</div>`
      }
      obj.push(val)
    }
    return obj
  })
  return data
}
//处理人到项目
function processPerson2Project (o) {
  let n = 1
  let owner = ''
  let data = o.map(item => {
    item.owner = (item.owner || '无').replaceAll(';', '')
    let obj = [
      n++,
      `<a href='https://www.tapd.cn/${item.workspace_id}/prong/tasks/view/${item.id}?action_entry_type=task_list' target='blank'>改</a>`,
      owner !== item.owner ? item.owner : '&nbsp;',
      workspaceMap[item.workspace_id],
      item.name.substring(0, 10),
      item.begin || '-',
      item.due || '-'
    ]
    owner = item.owner
    for (let i = 0; i < 30; i++) {
      let val //=item['date' + i]
      switch (item['date' + i]) {
        case 0:
          val = '&nbsp;'
          break
        case -1:
          val =
            '<div style="height:100%;margin:-8px;color:#CD2626;background:#CD2626">&nbsp;</div>'
          break
        case -2:
          val =
            '<div style="height:100%;margin:-8px;color:#CD2626;background:#CD2626">&nbsp;</div>'
          break
        case 1:
          val =
            '<div style="height:100%;margin:-8px;color:#B3EE3A;background:#B3EE3A">&nbsp;</div>'
          break
        default:
          val = '&nbsp;'
      }
      obj.push(val)
    }
    return obj
  })
  return data
}
//处理人到项目数量
function processPerson2Count (o) {
  let n = 1
  let owner = ''
  let data = o.map(item => {
    item.owner = (item.owner || '无').replaceAll(';', '')
    let obj = [
      n++,
      owner !== item.owner ? item.owner : '&nbsp;',
      workspaceMap[item.workspace_id],
      item['count(workspace_id)']
    ]
    owner = item.owner
    return obj
  })
  return data
}
async function getAllTapd (projectId) {
  //拼接所有任务
  let startDate = new Date()
  let endDate = new Date().dateAdd('d', 30)
  let taskTotalArr = []
  if (projectId) {
    const r = JSON.parse(await getTapd(projectId)) //取项目明细
    taskTotalArr = taskTotalArr.concat(task2Obj(r.data))
  } else {
    for (let i in workspaceMap) {
      const r = JSON.parse(await getTapd(i)) //取项目明细
      taskTotalArr = taskTotalArr.concat(task2Obj(r.data))
    }
  }

  taskTotalArr = taskTotalArr.orderBy(['owner'], ['asc'])
  //console.log(taskTotalArr)
  let nowDate = startDate
  let after30Date = endDate

  let r1 = taskItemAddDate(taskTotalArr, nowDate, after30Date)
  /* 2 */

  let tdTitle = ['序号', '处理人', '所属项目', '数量']
  for (let i = 0; i < 30; i++) {
    let pointDate = new Date()
    let dateRun = pointDate.dateAdd('d', i)
    let dateNum = dateRun.getDate()
    let val = dateNum < 10 ? '0' + dateNum : dateNum
    if (dateRun.getDay() === 0 || dateRun.getDay() === 6) {
      tdTitle.push(`<font color='red'>${val}</font>`)
    } else {
      tdTitle.push(val)
    }
  }
  let personProjectCount = []
  let ownerWorkspaceStr = ''
  for (let i = 0; i < r1.length; i++) {
    let itemObj = {
      owner: r1[i].owner,
      workspace_id: r1[i].workspace_id,
      taskCount: 1
    }
    let isFold = 0
    for (k = 0; k < 30; k++) {
      if (
        ownerWorkspaceStr !== r1[i].owner + '_' + r1[i].workspace_id ||
        i === 0
      ) {
        itemObj['date' + k] = r1[i]['date' + k]
      } else {
        personProjectCount[personProjectCount.length - 1][
          'date' + k
        ] += Math.abs(r1[i]['date' + k])
        isFold = 1
      }
    }
    ownerWorkspaceStr = r1[i].owner + '_' + r1[i].workspace_id
    if (!isFold) {
      personProjectCount.push(itemObj)
    } else {
      personProjectCount[personProjectCount.length - 1].taskCount++
    }
  }
  //console.log(personProjectCount)
  let outStr2 = genHtmlGrid(
    personProjectCount,
    tdTitle,
    'TAPD人员任务汇总 更新:' + new Date().date2Str(),
    processPersonProjectCount
  )

  /* 3 */
  tdTitle = [
    '序号',
    '操作',
    '处理人',
    '所属项目',
    '项目内容',
    '估计开始',
    '估计结束'
  ]
  for (let i = 0; i < 30; i++) {
    let pointDate = new Date()
    let dateRun = pointDate.dateAdd('d', i)
    let dateNum = dateRun.getDate()
    let val = dateNum < 10 ? '0' + dateNum : dateNum
    if (dateRun.getDay() === 0 || dateRun.getDay() === 6) {
      tdTitle.push(`<font color='red'>${val}</font>`)
    } else {
      tdTitle.push(val)
    }
  }

  let outStr3 = genHtmlGrid(
    r1.filter(item => {
      let diff = ((new Date(item.due) - new Date(item.begin)) / dateGap) | 0
      //console.log(diff)
      return !item.begin || !item.due || diff > 1
    }),
    tdTitle,
    '<font color="red">TAPD异常拆分[1.无开始结束时间 2.拆分周期>2天]</font>',
    processPerson2Project
  )
  return htmlOutModel.outHtml('TAPD汇总', outStr2 + '<br>' + outStr3)
}
module.exports = {
  async viewAll (ctx) {
    let { key, projectId } = ctx.checkedData.data
    key = 'xonfwb'
    if (
      ![
        'xonfwb',
        'bcxvkk',
        'daghlq',
        'rtyqez',
        'xirlia',
        'omqfmb',
        'wnuwhd',
        'papyat',
        'mvfkjy',
        'jwtjyd',
        'gxrbql',
        'zlapnl',
        'evvozm',
        'zoazxm',
        'afdidb',
        'znamvb',
        'avnddk',
        'hmrwyu',
        'toaaje',
        'zejflo'
      ].includes(key)
    ) {
      ctx.status = 405
      return
    }
    ctx.type = 'text/html'
    if (projectId) {
      ctx.body = await getAllTapd(projectId)
    } else {
      const nowDate = $.now()
      if (!global.tapdApi) {
        global.tapdApi = {
          t: nowDate,
          c: await getAllTapd()
        }
      } else {
        if (nowDate - global.tapdApi.t > 600000) {
          global.tapdApi = {
            t: nowDate,
            c: await getAllTapd()
          }
        } else {
          //console.log('covi 缓存')
        }
      }
      ctx.body = global.tapdApi.c
    }
  }
}

// 扩展函数
